package bigPack.web;

import bigPack.pojo.user;
import bigPack.service.UserService;
import bigPack.service.impl.UserServiceImpl;
import bigPack.utils.webUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class userSERVLET extends baseServlet {
    private UserService userService=new UserServiceImpl();
    //处理登录的功能
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        获取请求参数
        String username=req.getParameter("username");
        String password=req.getParameter("password");
//        调用userService.Login()处理业务
        user loginUser=userService.login(new user(null,username,password,null));
//        如果等于null,说明登录失败、
        if(loginUser==null){

            //把错误信息和回显的表单项信息，保存到request域中
            req.setAttribute("msg","用户名或密码错误");
            req.setAttribute("username",username);
            //登录失败，调回登录失败页
            req.getRequestDispatcher("/page/user/login.jsp").forward(req,resp);
        }else{
//            登录成功，调到登录成功页面
            req.getRequestDispatcher("/page/user/login_success.jsp").forward(req,resp);
        }
    }
    //处理注册的功能
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");


        user user=webUtil.copyParamToBean(req.getParameterMap(),new user());

        //检查验证码是否正确===写死，要求验证码为abcde
        if("abcde".equalsIgnoreCase(code)){
//            检查用户名是否正确
            if(userService.existsUsername(username)){
//            不可用
                //把回显信息保存到request域中
                req.setAttribute("msg","用户名已存在");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
//                调回注册界面
                req.getRequestDispatcher("/page/user/regist.jsp").forward(req,resp);
            }else {
//                可用，调用service保存到数据库
                userService.registeUser(new user(null,username,password,email));
//                调到注册成功界面
                req.getRequestDispatcher("/page/user/regist_success.jsp").forward(req,resp);
            }

        }else{
            //把回显信息保存到request域中
            req.setAttribute("msg","验证码错误");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            req.getRequestDispatcher("/page/user/regist.jsp").forward(req,resp);
        }
    }

}
